<template>
  <div class="page_view1">
    <el-card shadow="never" class="card-com">

      <div class="card-1">
        <searchPanel @refresh="init('reset')">
          <!-- 查询面板 -->
          <template v-slot:search>
            <el-form :inline="true" :model="initParams" class="demo-form-inline" label-width="120px">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品编码" style="width: 100%;">
                    <el-input @keyup.enter.native="init('search')" @clear="init('search')"
                      v-model="initParams.condition.productCode" clearable placeholder="请输入产品编码" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品名称">
                    <el-input @keyup.enter.native="init('search')" @clear="init('search')"
                      v-model="initParams.condition.productName" clearable placeholder="请输入产品名称" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品标题">
                    <el-input v-model="initParams.condition.productTitle" clearable @keyup.enter.native="init('search')"
                      @clear="init('search')" placeholder="请输入产品标题" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品副标题">
                    <el-input v-model="initParams.condition.productSubTitle" clearable
                      @keyup.enter.native="init('search')" @clear="init('search')" placeholder="请输入产品副标题" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品类型">
                    <BlackSelect v-model="initParams.condition.productType" @myChange="init('search')"
                      :options="productType"></BlackSelect>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="产品大类">
                    <BlackSelect v-model="initParams.condition.productCategoryCode" @myChange="init('search')"
                      :options="listCollect.totalProduct"></BlackSelect>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="供应商编码">
                    <el-select popper-class="no-wrap-popper" @change="init('search')" class="remote-select" clearable
                      v-model="initParams.condition.supplierCode" placeholder="请选择供应商" filterable collapse-tags>
                      <el-option :label="row.value" :value="row.key" :key="row.key"
                        v-for="row in listCollect.supplierList" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="是否展示">
                    <el-select v-model="initParams.condition.isShow" @change="init('search')" clearable
                      placeholder="请选择">
                      <el-option label="是" :value="1"></el-option>
                      <el-option label="否" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="运营商">
                    <el-select v-model="initParams.condition.isp" @change="init('search')" placeholder="请选择运营商"
                      clearable>
                      <el-option v-for="item in ispEnum" :key="item.id" :value="item.key"
                        :label="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :sd="12" :lg="8" :xl="6">
                  <el-form-item label="是否统计">
                    <el-select v-model="initParams.condition.isStatistics" @change="init('search')" clearable
                      placeholder="请选择是否统计">
                      <el-option label="是" :value="1"></el-option>
                      <el-option label="否" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

              </el-row>
              <el-row justify="end">
                <el-button type="primary" @click="init('search')">查询</el-button>
                <el-button @click="init('reset')">重置</el-button>
              </el-row>
            </el-form>
          </template>
          <!-- 字段添加 -->
          <template v-slot:edit>
            <el-button :icon="Plus" v-permission="'PRODUCT:CREATE-EDIT'" type="primary" title="新增产品"
              @click="addEdit('add')"></el-button>
            <el-button :icon="Download" v-permission="'PRODUCT:EXPORT'" title="下载产品列表" @click="btnDown"></el-button>
            <el-button :icon="List" v-permission="'PRODUCT:EXPORT'" title="查看下载产品列表" @click="btnDownList"></el-button>
            <DropItem v-model:table-prop="tableProp"></DropItem>

          </template>
        </searchPanel>
      </div>
      <div class="card-2">
        <OnlyTable ref="onlyTableRef" :tableProps="tableProp" :pageTotal="pageData.total" @get-page="handPage"
          :tableData="pageData.tableData" :tableHeight="pageData.tableHeight" :loading="pageData.loadIng">
          <template #isShow="scope">
            {{ isShow[scope.row.isShow] }}
          </template>
          <template #isp="scope">
            {{ isIsp[scope.row.isp] }}
          </template>
          <template #isStatistics="scope">
            {{ isStatistics[scope.row.isStatistics] }}
          </template>
          <template #supplier="scope">
            <el-tooltip class="box-item" effect="dark" :content="t(scope['row'])" placement="top-start">
              <span style="width: 100%" class="text_hide">
                {{ scope["row"]["supplierCode"] }}
              </span>
            </el-tooltip>
          </template>
          <template #handle="scope">

            <el-button type="primary" size="small" v-permission="'PRODUCT:CREATE-EDIT'" link
              @click="addEdit('edit', scope.row)">编辑</el-button>
            <el-button type="danger" size="small" v-permission="'PRODUCT:DELETE'" link
              @click="DeleteBtn(scope.row)">删除</el-button>
            <el-button type="primary" size="small" link @click="detailBtn(scope.row)">详情</el-button>
          </template>
        </OnlyTable>
      </div>
    </el-card>
    <Add ref="dialog" @tableFlush="tableFlush"></Add>
    <detailVue ref="detailVueRef"></detailVue>
    <Dialog :dialogProps="propsView" ref="dialogtwo" :info="info">
      <template #supplierExtInfo="scope">
        <template v-if="scope[scope.props.prop]">
          <template v-for="domain in convertFromExtInfoJson(scope[scope.props.prop])">
            <el-row style="width: 100%" justify="space-around">
              <el-col :span="8">
                <el-input v-model="domain.key" placeholder="请输入key" :autosize="{ minRows: 2, maxRows: 4 }"
                  :disabled="true" type="textarea"></el-input>
              </el-col>
              <el-col :span="15">
                <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" :disabled="true"
                  placeholder="请输入value" clearable></el-input>
              </el-col>
            </el-row>
          </template>
        </template>
      </template>
    </Dialog>
    <downList ref="downListRef" @flash="btnDownList"></downList>

  </div>

</template>
<script setup lang="ts">

import {
  getProductList,
  delProduct,
  getProductinfo,
  getSupplierAll
} from "@/api/product"
import { Plus, Download, List } from "@element-plus/icons-vue"
import { storeToRefs } from "pinia"
import { ref, onMounted, computed, nextTick, onUnmounted, defineAsyncComponent } from "vue"
import _ from "lodash"
import mittBus from '@/utils/mitt';
// import Add from "./comp/index.vue"
import config from "./config/index.ts"
import { ElMessage } from "element-plus"
import { productListStore } from "./pageStore.ts"
import useInstance from '@/hooks/useInstance';
import {
  exportExportProductApiPost,

} from "@/api/fileDown"
import { useEnumStore } from "@/store/enumeration.ts"
import { useComListData } from "@/store/list.ts"
import BlackSelect from "@/components/customSon/blackSelect.vue"
import DropItem from "@/components/customSon/dropItem.vue"
const onlyTableRef = ref()
const Add = defineAsyncComponent(() => import("./comp/index.vue"))
const detailVue = defineAsyncComponent(() => import('./comp/detail.vue'))
const { getSchemeList, getAllTotalProduct, getSupplierAllList, listCollect } = useComListData()

const { ispEnum, isIsp, isShow, isStatistics, productType } = storeToRefs(useEnumStore())
const { global } = useInstance();
const downListRef = ref<{ show: (title: string, row?: any) => void }>()

let { searchForm, dialogProps } = config
const { tableProp } = storeToRefs(productListStore())
let propsView = ref({ ...dialogProps })
let dialog = ref()
let detailVueRef = ref()
let dialogtwo = ref()

let info = ref({})

let initParams = ref({
  pageNum: 1,
  pageSize: 20,
  condition: {
    productCode: null,// 产品编码
    productName: null,// 产品名称
    productType: null,// 产品类型
    isShow: null,// 是否展示
    isp: null,// 运营商
    supplierCode: null,// 供应商
    productTitle: null,// 产品标题
    productSubTitle: null,// 产品标题
    isStatistics: null,// 是否统计
    productCategoryCode: null,// 产品大类
  },
  orders: ["created_time desc"]
})
const pageData = reactive({
  loadIng: false,
  tableData: [],
  total: 0,
  tableHeight: 500,
  tableList: [],
  supplierListAll: [] as any
})

const t = computed(() => {
  return function (scope: any) {
    return scope["supplierCode"] + " - " + scope["supplierName"]
  }
})



const convertFromExtInfoJson = (extInfoJson: any) => {
  const extInfoObj = JSON.parse(extInfoJson)
  const array = []
  for (let key in extInfoObj) {
    array.push({ key: key, value: extInfoObj[key] })
  }
  return array
}

const init = async (type: string) => {
  if (type == 'reset') {
    // @ts-ignore
    initParams.value.condition = {}
    initParams.value.pageNum = 1
    initParams.value.pageSize = 20
    onlyTableRef.value.initPagination()
  }

  pageData.loadIng = true
  getProductList(initParams.value).then((res) => {
    let {
      data: { records, total }
    } = res
    pageData.tableData = records && records.map((item: any) => {
      return {
        ...item,
        supplierExtInfo: item.supplierExtInfo == "{}" ? "" : item.supplierExtInfo,
        productType: productType.value[item.productType - 1]?.value
      }
    })
    mittBus.emit('scrollUpdate')
    pageData.total = total
    pageData.loadIng = false
  })
}
onMounted(() => {
  init('search')

  getSchemeList()
  getAllTotalProduct()
  getSupplierAllList()
})


const btnDownList = async () => {
  downListRef.value?.show('产品下载列表', 'product')
}
const btnDown = async () => {
  try {
    let res = await exportExportProductApiPost({ condition: initParams.value.condition })

    if (res && res.code == 20000) {
      ElMessage({
        type: "success",
        message: "下载成功 请查看下载列表 未出现下载数据 可等待在刷新下载列表！"
      })
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: "下载失败 请稍后再试！"
    })
  }
}
const detailBtn = async (row: any) => {
  getProductinfo({ id: row.id }).then((res) => {
    if (res.code == 20000) {
      let { data } = res
      detailVueRef.value?.handDiglogShow("详情")
      nextTick(() => {
        detailVueRef.value?.editModal(true, data)
      })
    }
  })
}
const DeleteBtn = async (row: any) => {
  const flag = await global.$myconfirm(`是否确定删除该数据？  ${row.productName}`)
  if (flag) {
    const res = await delProduct({ id: row.id })
    if (res.code == 20000) {
      ElMessage({
        type: "success",
        message: "数据删除成功"
      })
      init('search')
    } else {
      ElMessage({
        type: "error",
        message: "数据删除失败"
      })
    }
  }
}
const addEdit = async (type: string, row?: any) => {
  if (type == 'add') {
    dialog.value?.handDiglogShow("新建产品", 'add')
    dialog.value?.getSupplierList(listCollect.supplierList) // 减少请求
  } else {
    getProductinfo({ id: row.id }).then((res) => {
      if (res.code == 20000) {
        let { data } = res
        dialog.value?.handDiglogShow("编辑产品", 'edit')
        nextTick(() => {
          dialog.value?.getSupplierList(listCollect.supplierList) // 减少请求
          dialog.value?.editModal(true, data)
        })
      }
    })
  }

}


/*分页*/
const handPage = async (params: any) => {
  console.log(params, initParams.value.pageNum);

  if (params) {
    initParams.value.pageNum = params.pageNum
    initParams.value.pageSize = params.pageSize
  }

  init('search')
}
// 初始化table
const tableFlush = (type: string) => {
  console.log(type);
  if (type == 'add') {
    init('reset')
  } else {

    init('search')
  }
}

</script>

<style lang="scss" scope>
.page_view1 {
  height: calc(100vh - 70px);

  .card-com {
    display: flex;
    flex-direction: column;
  }
}
</style>
